<?php

namespace app\admin\controller;


use app\admin\model\SystemAdmin;
use app\admin\model\SystemQuick;
use app\common\controller\AdminController;
use think\App;
use think\facade\Db;
use think\facade\Env;

class Index extends AdminController
{

    /**
     * 后台主页
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        return $this->fetch('', [
            'admin' => session('admin'),
        ]);
    }

    /**
     * 后台欢迎页
     * @return string
     * @throws \Exception
     */
    public function welcome()
    {
        $quicks = SystemQuick::field('id,title,icon,href')
            ->where(['status' => 1])
            ->order('sort', 'desc')
            ->limit(8)
            ->select();
        $this->assign('quicks', $quicks);

        //用户统计
        $user_num = Db::name("user")->count();

        //产品数
        $service_goods = Db::name("service_goods")->count();

        //分销商统计
        $distributor = Db::name("user")->where("is_check",1)->count();
 
        //订单统计
        $order = Db::name("order")->where("status","in","2,3,4,7")->count();

        $this->assign('user_num', $user_num);
        $this->assign('service_goods', $service_goods);
        $this->assign('distributor', $distributor);
        $this->assign('order', $order);

        
        $expert_group = Db::name("expert_group")->order("id desc")->select();
        $expert_group = $expert_group->toArray();
        foreach($expert_group as $k=>$v){
            
            $service_technician = Db::name("service_technician")->where("expert_group_id",$v["id"])->field("id")
            ->paginate()->each(function($item){
                //获取本周开始时间和结束时间
                $beginLastweek=mktime(0,0,0,date('m'),date('d')-date('w')+1,date('Y'));
                $endLastweek=mktime(23,59,59,date('m'),date('d')-date('w')+7,date('Y'));
                $item["zhoumoney"] = Db::name("order")->whereBetween('create_time', [$beginLastweek, $endLastweek])->where("service_technician_id",$item["id"])->where("status",7)->sum("paidin_money");
                //php获取本月起始时间和结束时间
                $beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));
                $endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'));
                $item["yuemoney"] = Db::name("order")->whereBetween('create_time', [$beginThismonth, $endThismonth])->where("service_technician_id",$item["id"])->where("status",7)->sum("paidin_money");
                
                return $item;
            });
            $service_technician = $service_technician->toArray();
            $zhoumoney = array_column($service_technician["data"],"zhoumoney");
            $zhoumoney_sum = array_sum($zhoumoney);

            $yuemoney = array_column($service_technician["data"],"yuemoney");
            $yuemoney_sum = array_sum($yuemoney);
            
            $v["zhoumoney"] = $zhoumoney_sum;
            $v["yuemoney"] = $yuemoney_sum;
            $expert_group[$k] = $v;
        }
        //dump($expert_group);die;
      
        $expert_groupqwe = array_column($expert_group,"title");
        $zhoumoney = array_column($expert_group,"zhoumoney");
        $yuemoney = array_column($expert_group,"yuemoney");
        $this->assign('expert_group', implode(",",$expert_groupqwe));
        $this->assign('zhoumoney', implode(",",$zhoumoney));
        $this->assign('yuemoney', implode(",",$yuemoney));

        return $this->fetch();
    }

    /**
     * 修改管理员信息
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editAdmin()
    {
        $id = session('admin.id');
        $row = (new SystemAdmin())
            ->withoutField('password')
            ->find($id);
        empty($row) && $this->error('用户信息不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $this->isDemo && $this->error('正式环境下不允许修改');
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row
                    ->allowField(['head_img', 'phone', 'remark', 'update_time'])
                    ->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * 修改密码
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editPassword()
    {
        $id = session('admin.id');
        $row = (new SystemAdmin())
            ->withoutField('password')
            ->find($id);
        if (!$row) {
            $this->error('用户信息不存在');
        }
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $this->isDemo && $this->error('正式环境下不允许修改');
            $rule = [
                'password|登录密码'       => 'require',
                'password_again|确认密码' => 'require',
            ];
            $this->validate($post, $rule);
            if ($post['password'] != $post['password_again']) {
                $this->error('两次密码输入不一致');
            }

            // 判断是否为演示站点
            $example = Env::get('easyadmin.example', 0);
            $example == 1 && $this->error('演示站点不允许修改密码');

            try {
                $save = $row->save([
                    'password' => password($post['password']),
                ]);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

}
